package com.tx.websocket.demo.controller;

import com.tx.websocket.demo.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Map;

@Controller
public class IndexController {

    @GetMapping("/")
    public String index() {
        return "index/index";
    }

    @GetMapping("/login")
    public String login(User user) {
        return "index/login";
    }

    @PostMapping("/login")
    public String signIn(User user, Map<String, Object> map) {

        if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            map.put("errorMsg", "用户名和密码不能为空");
            return "index/login";
        }

        String encryptPassword = new Sha256Hash(user.getPassword()).toHex();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), encryptPassword, false);
        Subject currentUser = SecurityUtils.getSubject();

        try {
            if(!currentUser.isAuthenticated())
                currentUser.login(usernamePasswordToken);
        } catch(Exception e){
            map.put("errorMsg", e.getMessage());
            //返回异常信息,详情看ShiroRealm类
            return "index/login";
        }

        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout() {
        //清理登陆session
        SecurityUtils.getSubject().logout();
        return "index/login";
    }

    /**
     * 授权异常
     * @return 授权异常页面
     */
    @GetMapping("/unauth")
    public String unAuth() {
        return "index/unauth";
    }
}
